import copy

from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password, check_password
from django.conf import settings
from django.db.models import Q
from django.views import View
from django.http import HttpResponse
from django.db import transaction
from django.forms.models import modelformset_factory

from sales.forms import *
from sales.models import *
from utils.custom_paginator import Custom_page
from rbac.utils.permission_injection import init_permission


def login(request):
    if request.method == 'GET':
        login_form = Login_form()
        context = {
            'login_form': login_form,
        }
        return render(request, 'account/login.html', context)
    else:
        login_form = Login_form(request.POST)
        if login_form.is_valid():

            username = request.POST.get('username')
            password = request.POST.get('password')
            user = UserInfo.objects.filter(username=username).first()
            if check_password(password, user.password):
                # login(username)
                request.session['username'] = username
                init_permission(request, user)
                return redirect('sales:home')
            else:
                context = {
                    'login_form': login_form,
                }
                return render(request, 'account/login.html', context)

        else:
            context = {
                'login_form': login_form,
            }
            return render(request, 'account/login.html', context)


def register(request):
    if request.method == 'GET':
        register_form = Register_form()
        context = {
            'register_form': register_form,
        }
        return render(request, 'account/register.html', context)
    elif request.method == 'POST':

        register_form = Register_form(request.POST)
        if register_form.is_valid():
            data = register_form.cleaned_data
            data['password'] = make_password(data['password'])
            data.pop('re_password')
            new_user = UserInfo.objects.create(**data)
            return redirect('sales:login')
        else:
            context = {'register_form': register_form}
            return render(request, 'account/register.html', context)


def logout(request):
    request.session.flush()
    return redirect('sales:login')


class CustomerView(View):
    def get(self, request):
        username = self.request.session.get('username')
        path = self.request.path  # current path

        recv_data = copy.copy(request.GET)
        current_page_number = request.GET.get('page')  # 当前页码
        search_field = request.GET.get('search_field')  # 搜索条件
        keyword = request.GET.get('keyword')  # 搜索数据   陈

        if keyword:
            q = Q()  # 实例化q对象
            q.children.append([search_field, keyword])  #
            all_customers = Customer.objects.filter(q)
        else:
            search_field = 'qq__contains'
            all_customers = Customer.objects.all()

        if path == '/customer/':
            # 筛选所有公户的客户信息
            tag = '1'
            all_customers = all_customers.filter(consultant__isnull=True)
        else:
            tag = '0'
            all_customers = all_customers.filter(consultant__username=username)

        total_count = all_customers.count()
        per_page_count = settings.PER_PAGE_COUNT
        page_number_show = settings.PAGE_NUMBER_SHOW
        page_obj = Custom_page(current_page_number, total_count, per_page_count, page_number_show, recv_data)
        all_customers = all_customers[page_obj.start_data_number:page_obj.end_data_number]
        page_html = page_obj.page_html_func()
        context = {'page_html': page_html,
                   'keyword': keyword,
                   'all_customers': all_customers,
                   'search_field': search_field,
                   'tag': tag,
                   }
        return render(request, 'customer/customer.html', context)

    def post(self, request):

        action = request.POST.get('action')
        selected_pk_list = request.POST.getlist('pk')  # 选中的客户的

        if hasattr(self, action):
            ret = getattr(self, action)(request, selected_pk_list)
            if ret:
                return ret
            else:
                return redirect(request.path)
        else:
            return HttpResponse('你的方法不对!!')

    def bulk_delete(self, request, selected_pk_list):
        # delete selected customer
        customer_list = Customer.objects.filter(id__in=selected_pk_list, consultant__isnull=True)
        customer_list.delete()
        return redirect(request.path)

    def reverse_gs(self, request, selected_pk_list):
        # reverse public customer to private customer
        with transaction.atomic():
            customer_list = Customer.objects.filter(id__in=selected_pk_list, consultant__isnull=True)

        if customer_list.count() != len(selected_pk_list):
            # someone already select this consumers

            return redirect('sales:customer')

        username = self.request.session.get('username')
        user_obj = UserInfo.objects.get(username=username)
        customer_list.update(consultant_id=user_obj.id)

    def reverse_sg(self, request, selected_pk_list):
        # reverse private customer to public customer
        customer_list = Customer.objects.filter(id__in=selected_pk_list, consultant__isnull=True)
        customer_list.update(consultant=None)


def add_edit_customer(request, pk=None):
    label = '编辑用户' if pk else '添加用户'
    customer_obj = Customer.objects.filter(pk=pk).first()
    if request.method == 'GET':
        customer_form = CustomerModelForm(instance=customer_obj)
        context = {
            'customer_form': customer_form,
            'label': label,
        }
        return render(request, 'customer/add_edit_customer.html', context)
    elif request.method == 'POST':
        next_path = request.GET.get('next')
        customer_form = CustomerModelForm(request.POST, instance=customer_obj)
        if customer_form.is_valid():
            customer_form.save()
            return redirect(next_path)
        else:
            context = {
                'customer_form': customer_form,
                'label': 'label',
            }
            return render(request, 'customer/add_edit_customer.html', context)


class ConsultRecordView(View):
    def get(self, request):
        username = request.session.get('username')
        user = UserInfo.objects.get(username=username)
        search_field = request.GET.get('search_field')
        keyword = request.GET.get('keyword')

        customer_id = request.GET.get('customer_id')

        if keyword:
            q = Q()  # 实例化q对象
            q.children.append([search_field, keyword])  #
            all_consult_records = ConsultRecord.objects.filter(q)
        else:
            all_consult_records = ConsultRecord.objects.all()

        if customer_id:
            all_consult_records.filter(customer_id=customer_id)

        all_consult_records = all_consult_records.filter(consultant=user, delete_status=False)
        recv_data = copy.copy(request.GET)
        current_page_number = request.GET.get('page')
        total_count = all_consult_records.count()
        per_page_count = settings.PER_PAGE_COUNT
        page_number_show = settings.PAGE_NUMBER_SHOW

        page_obj = Custom_page(current_page_number, total_count, per_page_count, page_number_show, recv_data)
        all_consult_records = all_consult_records[page_obj.start_data_number:page_obj.end_data_number]
        page_html = page_obj.page_html_func()
        context = {'page_html': page_html,
                   'all_consult_records': all_consult_records,
                   'search_field': search_field,
                   'keyword': keyword,
                   }
        return render(request, 'consult_record/consult_record.html', context)

    def post(self, request):

        action = request.POST.get('action')
        selected_pk_list = request.POST.getlist('pk')  # selected consumer's pk list

        consult_record_list = ConsultRecord.objects.filter(id__in=selected_pk_list)

        if hasattr(self, action):
            ret = getattr(self, action)(request, consult_record_list)
            if ret:
                return ret
            else:
                return redirect(request.path)
        else:
            return HttpResponse('你的方法不对!!')

    def bulk_delete(self, request, consult_record_list):
        # delete action just update the status to True
        consult_record_list.update(delete_status=True)
        return redirect(request.path)


def add_edit_consult_record(request, pk=None):
    consult_record_obj = ConsultRecord.objects.filter(pk=pk).first()
    label = '编辑跟进记录' if pk else '添加记录'

    if request.method == 'GET':
        consult_record_form = ConsultRecordModelForm(request, instance=consult_record_obj)
        context = {
            'consult_record_form': consult_record_form,
        }

        return render(request, 'consult_record/add_edit_consult_record.html', context)
    else:
        next_path = request.GET.get('next')
        consult_record_form = ConsultRecordModelForm(request, request.POST, instance=consult_record_obj)
        if consult_record_form.is_valid():
            consult_record_form.save()
            return redirect('sales:consult_record') if not pk else redirect(next_path)
        else:
            context = {
                'consult_record_form': consult_record_form,
            }
            return render(request, 'consult_record/add_edit_consult_record.html', context)


class EnrollmentView(View):
    def get(self, request):
        username = request.session.get('username')
        user = UserInfo.objects.get(username=username)
        search_field = request.GET.get('search_field')
        keyword = request.GET.get('keyword')

        if keyword:
            q = Q()
            q.children.append([search_field, keyword])
            all_enrollments = Enrollment.objects.filter(q)
        else:
            all_enrollments = Enrollment.objects.all()

        all_enrollments = all_enrollments.filter(customer__consultant=user)
        recv_data = copy.copy(request.GET)
        current_page_number = request.GET.get('page')
        total_count = all_enrollments.count()
        per_page_count = settings.PER_PAGE_COUNT
        page_number_show = settings.PAGE_NUMBER_SHOW

        page_obj = Custom_page(current_page_number, total_count, per_page_count, page_number_show, recv_data)
        all_enrollments = all_enrollments[page_obj.start_data_number:page_obj.end_data_number]

        page_html = page_obj.page_html_func()

        context = {
            'page_html': page_html,
            'all_enrollments': all_enrollments,
            'search_field': search_field,
            'keyword': keyword,
        }

        return render(request, 'enrollment/enrollment.html', context)

    def post(self, request):
        action = request.POST.get('action')
        selected_pk_list = request.POST.getlist('pk')  # selected consumer's pk list

        enrollment_list = Enrollment.objects.filter(id__in=selected_pk_list)

        if hasattr(self, action):
            ret = getattr(self, action)(request, enrollment_list)
            if ret:
                return ret
            else:
                return redirect(request.path)
        else:
            return HttpResponse('你的方法不对!!')

    def bulk_delete(self, request, enrollment_list):
        # delete action just update the status to True
        enrollment_list.update(delete_status=True)
        return redirect(request.path)


def add_edit_enrollment(request, pk=None):
    enrollment_obj = Enrollment.objects.filter(pk=pk).first()
    label = '编辑注册信息' if pk else '添加注册信息'
    if request.method == 'GET':
        enrollment_form = EnrollmentModelForm(instance=enrollment_obj)
        context = {
            'enrollment_form': enrollment_form,
        }
        return render(request, 'enrollment/add_edit_enrollment.html', context)
    else:
        next_path = request.GET.get('next')
        enrollment_form = EnrollmentModelForm(request.POST, instance=enrollment_obj)
        if enrollment_form.is_valid():
            enrollment_form.save()
            return redirect('sales:enrollment') if not pk else redirect(next_path)
        else:
            context = {
                'enrollment_form': enrollment_form,
            }
            return render(request, 'enrollment/add_edit_enrollment.html', context)


class CourseRecordView(View):
    def get(self, request):
        username = request.session.get('username')
        user = UserInfo.objects.get(username=username)
        search_field = request.GET.get('search_field')
        keyword = request.GET.get('keyword')

        if keyword:
            q = Q()
            q.children.append([search_field, keyword])
            all_courserecords = CourseRecord.objects.filter(q)
        else:
            all_courserecords = CourseRecord.objects.all()

        recv_data = copy.copy(request.GET)
        current_page_number = request.GET.get('page')
        total_count = all_courserecords.count()
        per_page_count = settings.PER_PAGE_COUNT
        page_number_show = settings.PAGE_NUMBER_SHOW

        page_obj = Custom_page(current_page_number, total_count, per_page_count, page_number_show, recv_data)
        all_courserecords = all_courserecords[page_obj.start_data_number:page_obj.end_data_number]

        page_html = page_obj.page_html_func()

        context = {
            'page_html': page_html,
            'all_courserecords': all_courserecords,
            'search_field': search_field,
            'keyword': keyword,
        }

        return render(request, 'course_record/course_record.html', context)

    def post(self, request):
        action = request.POST.get('action')
        selected_pk_list = request.POST.getlist('pk')  # selected consumer's pk list

        course_record_list = Enrollment.objects.filter(id__in=selected_pk_list)

        if hasattr(self, action):
            ret = getattr(self, action)(request, course_record_list)
            if ret:
                return ret
            else:
                return redirect(request.path)
        else:
            return HttpResponse('你的方法不对!!')

    def bulk_delete(self, request, course_record_list):
        # delete action just update the status to True
        course_record_list.update(delete_status=True)
        return redirect(request.path)


def add_edit_course_record(request, pk=None):
    course_record_obj = CourseRecord.objects.filter(pk=pk).first()
    label = '编辑注册信息' if pk else '添加注册信息'
    if request.method == 'GET':
        course_record_form = CourseRecordModelForm(instance=course_record_obj)
        context = {
            'course_record_form': course_record_form,
        }
        return render(request, 'course_record/add_edit_course_record.html', context)
    else:
        next_path = request.GET.get('next')
        course_record_form = CourseRecordModelForm(request.POST, instance=course_record_obj)
        if course_record_form.is_valid():
            course_record_form.save()
            return redirect('sales:course_record') if not pk else redirect(next_path)
        else:
            context = {
                'course_record_form': course_record_form,
            }
            return render(request, 'course_record/add_edit_course_record.html', context)


class StudyRecordView(View):
    def get(self, request, course_id):
        formset_obj = modelformset_factory(model=StudyRecord, form=StudyRecordModelForm, extra=0)
        formset = formset_obj(queryset=StudyRecord.objects.filter(course_record_id=course_id))
        return render(request, 'study_record/study_record.html', {'formset': formset})

    def post(self, request, course_id):
        formset_obj = modelformset_factory(model=StudyRecord, form=StudyRecordModelForm, extra=0)
        formset = formset_obj(request.POST)
        if formset.is_valid():
            formset.save()
            return redirect(request.path)
        else:
            return render(request, 'study_record/study_record.html', {'formset': formset})
        # search_field = request.GET.get('search_field')
        # keyword = request.GET.get('keyword')
        #
        # if keyword:
        #     q = Q()
        #     q.children.append([search_field, keyword])
        #     all_studyrecords = StudyRecord.objects.filter(q)
        # else:
        #     all_studyrecords = StudyRecord.objects.all()
        #
        # recv_data = copy.copy(request.GET)
        # current_page_number = request.GET.get('page')
        # total_count = all_studyrecords.count()
        # per_page_count = settings.PER_PAGE_COUNT
        # page_number_show = settings.PAGE_NUMBER_SHOW
        #
        # page_obj = Custom_page(current_page_number, total_count, per_page_count, page_number_show, recv_data)
        # all_studyrecords = all_studyrecords[page_obj.start_data_number:page_obj.end_data_number]
        #
        # page_html = page_obj.page_html_func()
        # context = {
        #     'page_html': page_html,
        #     'all_studyrecords': all_studyrecords,
        #     'search_field': search_field,
        #     'keyword': keyword,
        # }
        #
        # return render(request, 'study_record/study_record.html', context)

    # def post(self, request):
    #     action = request.POST.get('action')
    #     selected_pk_list = request.POST.getlist('pk')
    #
    #     study_record_list = StudyRecord.objects.filter(id__in=selected_pk_list)
    #
    #     if hasattr(self, action):
    #         ret = getattr(self, action)(request, study_record_list)
    #         if ret:
    #             return ret
    #         else:
    #             return redirect(request.path)
    #     else:
    #         return HttpResponse('你的方法不对')
    #
    # def bulk_delete(self, request, study_record_list):
    #     study_record_list.update(delete_status=True)
    #     return redirect(request.path)


def add_edit_study_record(request, pk=None):
    study_record_obj = StudyRecord.objects.filter(pk=pk).first()
    label = '编辑学习记录' if pk else '添加学习记录'
    if request.method == 'GET':
        study_record_form = StudyRecordModelForm(instance=study_record_obj)
        context = {
            'study_record_form': study_record_form,
        }
        return render(request, 'study_record/add_edit_study_record.html', context)
    else:
        next_path = request.GET.get('next')
        study_record_form = StudyRecordModelForm(request.POST, instance=study_record_obj)
        if study_record_form.is_valid():
            study_record_form.save()
            return redirect('sales:study_record') if not pk else redirect(next_path)
        else:
            context = {
                'study_record_form': study_record_form,
            }
            return render(request, 'study_record/add_edit_study_record.html', context)
